package com.bungarus.busi;

import com.bungarus.Access;
import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.MessageType;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.util.StringUtils;

/**
 *
 * Created by tang on 2018/11/11.
 */
@ChannelHandler.Sharable
public class ServerAuthHandler extends ChannelInboundHandlerAdapter {
    private final Access access;

    public ServerAuthHandler(Access access) {
        this.access = access;
    }

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        MessageProtobuf.Message message = (MessageProtobuf.Message)msg;
        if(MessageType.ACK != message.getHeader().getType() &&
                MessageType.HEARTBEAT_PING != message.getHeader().getType()) {
            MessageProtobuf.Header header = message.getHeader();
            MessageProtobuf.Credential credential = message.getHeader().getCredential();

            if(StringUtils.isEmpty(header.getDev())) { //client must send the device info
                channelHandlerContext.fireExceptionCaught(new AuthenticationInputException());
            }
            else if (StringUtils.isEmpty(header.getSessionId())
                    && StringUtils.isEmpty(header.getToken())
                    && StringUtils.isEmpty(credential.getUsername())
                    && StringUtils.isEmpty(credential.getPwd())) {

                channelHandlerContext.fireExceptionCaught(new AuthenticationInputException());
            }
            else {
                new Authentication(channelHandlerContext, this.access).doBusiness(msg);
            }
        }
        else {
            super.channelRead(channelHandlerContext, msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        super.exceptionCaught(channelHandlerContext, throwable);
    }
}
